package org.example.selector;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * 服务端
 */
public class Demo1Service {
    public static void main(String[] args) {
        //创建ServerSocket通道和选择器
        try (ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
             Selector selector = Selector.open()) {
            //设置端口和非阻塞
            serverSocketChannel.bind(new InetSocketAddress(10040));
            serverSocketChannel.configureBlocking(false);
            //ServerSocket注册至选择器
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            //循环监听
            while (!serverSocketChannel.socket().isClosed()) {
                //轮询事件,如无连接则进入下一次循环
                if (selector.select(1000) == 0) {
                    System.out.println("等待一秒,无连接");
                    continue;
                }
                //遍历选择
                for (SelectionKey key : selector.selectedKeys()) {
                    //如果为连接
                    if (key.isAcceptable()) {
                        //获取socket通道,并设置非阻塞
                        SocketChannel socketChannel = serverSocketChannel.accept();
                        socketChannel.configureBlocking(false);
                        System.out.println("连接成功");
                        //注册读取事件至选择器
                        socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                    }
                    //如果为读取
                    if (key.isReadable()) {
                        //获取socket通道和缓冲区
                        try (SocketChannel socketChannel = (SocketChannel) key.channel()) {
                            ByteBuffer byteBuffer = (ByteBuffer) key.attachment();
                            //读取数据至缓冲区并打印
                            socketChannel.read(byteBuffer);
                            System.out.println("读取数据" + new String(byteBuffer.array()));
                        }
                    }
                    //删除事件
                    selector.selectedKeys().remove(key);
                }
                System.out.println(selector.keys().size());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
